//
//  AppDelegate.m
//  MiBaoTu
//
//  Created by 彭鹏 on 16/9/18.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import "GuideViewController.h"
#import "MBLoginController.h"
#import "WelcomeViewController.h"
#import <WeiboSDK.h>
#import "NSString+MD5String.h"
#import "MBTabBarController.h"
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "MBNavController.h"
#import "Reachability.h"
#import <MediaPlayer/MediaPlayer.h>

#import <UMMobClick/MobClick.h>


@interface AppDelegate ()<WXApiDelegate,WeiboSDKDelegate,QQApiInterfaceDelegate,TencentSessionDelegate> {
    Reachability            *_hostReachability;
}

@end

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //设置自动登录
    [self loadDataForLogin];
    [self preventImagePickerCrashOn3DTouch];
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //设置导航栏的背景颜色
    [[UINavigationBar appearance] setBarTintColor:TINK_BG_COLOR];
    //后台播放
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //默认情况下扬声器播放
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    //数据库
    [self setDateForDB];
    //设置导航栏上文字的颜色）
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:UIColorFromHex(0xffffff)}];
    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleLightContent];

    GuideViewController *guide = [[GuideViewController alloc]init];
    self.window.rootViewController = guide;
    [self.window makeKeyAndVisible];

    //设置分享
    [CLShareManager setShareAppKey];
    //微博登录
    [WeiboSDK registerApp:K_Sina_AppKey];
    //微信登录
    [WXApi registerApp:K_WX_AppID withDescription:@"Wechat"];
    //QQ登录
    [[TencentOAuth alloc] initWithAppId:K_QQ_AppId andDelegate:self];
    //统计
    UMConfigInstance.appKey = K_UM_AppKey;
    UMConfigInstance.ChannelId = @"App Store";
    [MobClick startWithConfigure:UMConfigInstance];
    NSString *infoStr = [[[NSBundle mainBundle]infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:infoStr];
    [MobClick setEncryptEnabled:YES];
    
    
      
    // 检测指定服务器是否可达
    NSString *remoteHostName = @"www.bing.com";
    _hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
    [_hostReachability startNotifier];
    // Reachability使用了通知，当网络状态发生变化时发送通知kReachabilityChangedNotification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appReachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:nil];
    
     return YES;
}
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    if (ISIPAD) {
        return UIInterfaceOrientationMaskLandscapeRight;
    }
    return UIInterfaceOrientationMaskPortrait;
}

// 分享回调方法
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([url.absoluteString hasPrefix:[NSString stringWithFormat:@"tencent%@",K_QQ_AppId]]) {
        [QQApiInterface handleOpenURL:url delegate:self];
        return [TencentOAuth HandleOpenURL:url];
    }
    else if ([url.absoluteString hasPrefix:[NSString stringWithFormat:@"wb%@",K_Sina_AppKey]]) {
        return [WeiboSDK handleOpenURL:url delegate:self];
    }
    else if ([url.absoluteString hasPrefix:[NSString stringWithFormat:@"%@",K_WX_AppID]]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}
//QQ登录-------------------------------------
/**
 处理来至QQ的请求
 */
- (void)onReq:(QQBaseReq *)req{
    NSLog(@" ----req %@",req);
}

/**
 处理QQ在线状态的回调
 */
- (void)isOnlineResponse:(NSDictionary *)response{
    
}
//微信登录------------------------------------
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    if ([url.absoluteString hasPrefix:[NSString stringWithFormat:@"tencent%@",K_QQ_AppId]]) {
        [QQApiInterface handleOpenURL:url delegate:self];
        return [TencentOAuth HandleOpenURL:url];
        
    }
    
    return [WXApi handleOpenURL:url delegate:self];
}
-(void) onResp:(BaseResp*)resp{
    
    // SendMessageToQQResp应答帮助类
    if ([resp.class isSubclassOfClass: [SendMessageToQQResp class]]) {  //QQ分享回应
        if (_qqDelegate) {
            if ([_qqDelegate respondsToSelector:@selector(shareSuccssWithQQCode:)]) {
                SendMessageToQQResp *msg = (SendMessageToQQResp *)resp;
                [_qqDelegate shareSuccssWithQQCode:[msg.result integerValue]];
            }
        }
    }
    NSLog(@"resp %d",resp.errCode);
    
    if ([resp isKindOfClass:[SendAuthResp class]]) {   //授权登录的类。
        if (resp.errCode == 0) {  //成功。
            //这里处理回调的方法 。 通过代理吧对应的登录消息传送过去。
            if ([_wxDelegate respondsToSelector:@selector(loginSuccessByCode:)]) {
                SendAuthResp *resp2 = (SendAuthResp *)resp;
                [_wxDelegate loginSuccessByCode:resp2.code];
            }
        }else{ //失败
            NSLog(@"error %@",resp.errStr);
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登录失败" message:[NSString stringWithFormat:@"reason : %@",resp.errStr] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
    }
}

//微博登录------------------------------------
// 9.0 后才生效
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options{
    if ([url.absoluteString hasPrefix:[NSString stringWithFormat:@"tencent%@",K_QQ_AppId]]) {
        [QQApiInterface handleOpenURL:url delegate:self];
        return [TencentOAuth HandleOpenURL:url];
    }
    else if ([url.absoluteString hasPrefix:[NSString stringWithFormat:@"%@",K_WX_AppID]]) {
        return [WXApi handleOpenURL:url delegate:self];
    }
    return [WeiboSDK handleOpenURL:url delegate:self];
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response{
    if ([response isKindOfClass:WBAuthorizeResponse.class])  //微博登录的回调
    {
        if ([_weiboDelegate respondsToSelector:@selector(weiboLoginByResponse:)]) {
            [_weiboDelegate weiboLoginByResponse:response];
        }
    }
    
}

- (void)setDateForDB
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:MusicCachesDirectory]) {
        [fileManager createDirectoryAtPath:MusicCachesDirectory withIntermediateDirectories:YES attributes:nil error:NULL];
    }
    
    NSArray *musicArr = [[FMManageObject standerDefault]onSelectCustomMusicFileCount];
    if (musicArr.count > 0) {
        [UserManager standerDefult].downedMusicArr = [[NSMutableArray alloc]initWithArray:musicArr];
    }
    
    //歌曲列表 缓存显示上一次退出程序的歌曲列表
    NSArray *musicListArr = [NSKeyedUnarchiver unarchiveObjectWithFile:[MusicCachesDirectory stringByAppendingPathComponent:@"collectionMusic.data"]];
    if (musicListArr.count > 0) {
        [[UserManager standerDefult].musicArr addObjectsFromArray:musicListArr];
        //当前第几首歌以及类型播放器
        NSString *currentNumStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"music_list_CurrentNum"];
        NSString *currentTypeStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"music_Type_CurrentNum"];
        if ([currentTypeStr intValue] == 0) {
            [[UserManager standerDefult]setAudioPlayerType:AudioPLayerType_YinPin];
            NSNumber *isOnline =  [[NSUserDefaults standardUserDefaults]objectForKey:@"isOnlineForMusic"];
            if ([isOnline isKindOfClass:[NSNumber class]]) {
                [[UserManager standerDefult]setIsOnlinePlayer:[isOnline boolValue]];
            } else {
                [[UserManager standerDefult]setIsOnlinePlayer:NO];
            }
        }
        else if ([currentTypeStr intValue] == 2) {
            [[UserManager standerDefult]setAudioPlayerType:AudioPLayerType_Qinzix];
            NSArray *qinzixiuLastArr = [NSKeyedUnarchiver unarchiveObjectWithFile:[MusicCachesDirectory stringByAppendingPathComponent:@"last_qinzixiu.data"]];
            if (qinzixiuLastArr.count > 0) {
                [[UserManager standerDefult].qinzixiuArr addObjectsFromArray:qinzixiuLastArr];
            }
        }
        else if ([currentTypeStr intValue] == 3) {
             NSDictionary *zhuboLastDic = [NSKeyedUnarchiver unarchiveObjectWithFile:[MusicCachesDirectory stringByAppendingPathComponent:@"last_qinzixiu.data"]];
            if (zhuboLastDic) {
                [[UserManager standerDefult].zhuboDic addEntriesFromDictionary:zhuboLastDic];
            }
            [[UserManager standerDefult]setAudioPlayerType:AudioPLayerType_ZhuBo];
        }
        [[UserManager standerDefult]setSelectMusicIndex:[currentNumStr integerValue]];
        
        //删除记录
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:[MusicCachesDirectory stringByAppendingPathComponent:@"collectionMusic.data"]]) {
            [fileManager removeItemAtPath:[MusicCachesDirectory stringByAppendingPathComponent:@"collectionMusic.data"] error:nil];
        }
        if ([fileManager fileExistsAtPath:[MusicCachesDirectory stringByAppendingPathComponent:@"last_qinzixiu.data"]]) {
            [fileManager removeItemAtPath:[MusicCachesDirectory stringByAppendingPathComponent:@"last_qinzixiu.data"] error:nil];
        }
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"music_list_CurrentNum"];
        [[NSUserDefaults standardUserDefaults]setObject:nil forKey:@"music_Type_CurrentNum"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
}

- (void)setUpTabbar:(BOOL)isTabbar
{
    if (isTabbar) {
        UserModel *model = [UserManager standerDefult].userModel;
        if (!model) {
            MBLoginController *loginVC = [[MBLoginController alloc] init];
            loginVC.isFormTabbar = YES;
            MBNavController *nav = [[MBNavController alloc] initWithRootViewController:loginVC];
            self.window.rootViewController = nav;
        } else {
            MBTabBarController *tabBar = [[MBTabBarController alloc] init];
            self.window.rootViewController = tabBar;
        }
        
    } else {
        WelcomeViewController *welcome = [[WelcomeViewController alloc]init];
        self.window.rootViewController = welcome;
        
        [[NSUserDefaults standardUserDefaults]setObject:@"FIRST_GUIDE_SHOW" forKey:@"FIRST_GUIDE_SHOW"];
        [[NSUserDefaults standardUserDefaults]synchronize];
    }
}

- (void)loadDataForLogin
{
    NSString *login_phone = [[NSUserDefaults standardUserDefaults]objectForKey:@"login_phone"];
    if (login_phone.length > 0) {
        //有登录记录
        NSDate *date = [NSDate date];
        NSDateFormatter  *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyyMMdd"];
        NSString *dateStr = [formatter stringFromDate:date];
        NSString *login_answer = [[NSUserDefaults standardUserDefaults]objectForKey:@"login_answer"];
        NSArray *loginArr = [login_answer componentsSeparatedByString:@"_"];
        if (loginArr.count > 1) {
            NSString *answerTime = loginArr[0];
            NSDate *answerDate = [formatter dateFromString:answerTime];
            NSTimeInterval time1 = [answerDate timeIntervalSince1970];
            NSDate *nDate = [formatter dateFromString:dateStr];
            NSTimeInterval time2 = [nDate timeIntervalSince1970];
            NSTimeInterval cha = time2 - time1;
            NSString *timeString = [NSString stringWithFormat:@"%f",cha/86400];
            timeString = [timeString substringToIndex:timeString.length-7];
            if ([timeString intValue] <= 30) {
                //密码保存30天内有效
                [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:LOGIN_URL_PATH,login_phone,[NSString stringWithMD5Encrypt:loginArr[1]]] view:nil success:^(NSDictionary * json) {
                    
             
                    if ([json[@"ret_code"] integerValue]==0) {
                        //信息保存
                        NSDictionary *data = json[@"data"];
                        if (data.allKeys.count == 0) return ;
                        UserModel *model = [UserModel objectWithKeyValues:data];
                        [[UserManager standerDefult] setUserModel:model];
                        
                        NSArray *collecitonArr = json[@"AudioIDList"];
                        if ([collecitonArr isKindOfClass:[NSArray class]]) {
                            [[UserManager standerDefult].collectionMusicArr removeAllObjects];
                            [[UserManager standerDefult].collectionMusicArr addObjectsFromArray:collecitonArr];
                        }
                        NSArray *colleciton2Arr = json[@"AlbumIDList"];
                        if ([colleciton2Arr isKindOfClass:[NSArray class]]) {
                            [[UserManager standerDefult].collectionAlbumArr removeAllObjects];
                            [[UserManager standerDefult].collectionAlbumArr addObjectsFromArray:colleciton2Arr];
                        }
                        NSArray *colleciton3Arr = json[@"ShowIDList"];
                        if ([colleciton3Arr isKindOfClass:[NSArray class]]) {
                            [[UserManager standerDefult].collectionShowArr removeAllObjects];
                            [[UserManager standerDefult].collectionShowArr addObjectsFromArray:colleciton3Arr];
                        }
                        NSArray *praiseListArr = json[@"PraiseList"];
                        if ([praiseListArr isKindOfClass:[NSArray class]]) {
                            [[UserManager standerDefult].praiseListArr removeAllObjects];
                            [[UserManager standerDefult].praiseListArr addObjectsFromArray:praiseListArr];
                        }

                        //统计
                        [MobClick profileSignInWithPUID:login_phone];
                        
                        //保存密码
                        NSDate *date = [NSDate date];
                        NSDateFormatter  *formatter = [[NSDateFormatter alloc]init];
                        [formatter setDateFormat:@"yyyyMMdd"];
                        NSString *dateStr = [formatter stringFromDate:date];
                        [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@_%@",dateStr,loginArr[1]] forKey:@"login_answer"];
                        [[NSUserDefaults standardUserDefaults]setObject:login_phone forKey:@"login_phone"];
                        [[NSUserDefaults standardUserDefaults]setObject:@{} forKey:@"three_login"];
                        [[NSUserDefaults standardUserDefaults]synchronize];
                        
                    }
                } failure:^(NSError *error) {

                }];
                
            }
        }
    }
    else {
        NSDictionary *three_login = [[NSUserDefaults standardUserDefaults]objectForKey:@"three_login"];
        if ([three_login isKindOfClass:[NSDictionary class]]) {
            if (three_login.allKeys.count > 0) {
                //默认第三方登录
                NSString *_openID = [three_login objectForKey:@"openId"];
                NSString *_nickName = [three_login objectForKey:@"nickName"];
                NSString *_picImgName = [three_login objectForKey:@"picImg"];
                NSNumber *num = [three_login objectForKey:@"type"];
                if ([_openID isKindOfClass:[NSString class]]) {
                    if (_openID.length == 0) {
                        return;
                    }
                }
                if ([_nickName isKindOfClass:[NSString class]]) {
                    if (_nickName.length == 0) {
                        return;
                    }
                }
                if ([_picImgName isKindOfClass:[NSString class]]) {
                    if (_picImgName.length == 0) {
                        return;
                    }
                }
                if ([num isKindOfClass:[NSNumber class]]) {
                    if ([num intValue] == 0) {
                        return;
                    }
                }
                [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:VERIFICATION_THIRDLOGIN_URL_PATH,num,_openID,_nickName,_picImgName] view:nil success:^(id json) {

                    //0 注册成功 1已经注册
                    if ([json[@"ret_code"] intValue] == 0) {
                        //注册成功 设置属性
                        NSDictionary *data = json[@"data"];
                        if (data.allKeys.count == 0) return ;
                        
                        UserModel *model = [UserModel objectWithKeyValues:data];
                        [[UserManager standerDefult] setUserModel:model];
                        
                        //保留第三方登录信息
                        NSDictionary *dic = @{@"openId":_openID,
                                              @"nickName":_nickName,
                                              @"picImg":_picImgName,
                                              @"type":num};
                        [[NSUserDefaults standardUserDefaults]setObject:dic forKey:@"three_login"];
                        [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"login_phone"];
                        [[NSUserDefaults standardUserDefaults]synchronize];
                        
                    }
                    else if ([json[@"ret_code"] intValue] == 1) {
                        //已注册
                        NSDictionary *data = json[@"data"];
                        if (data.allKeys.count == 0) return ;
                        
                        UserModel *model = [UserModel objectWithKeyValues:data];
                        [[UserManager standerDefult] setUserModel:model];
                        
                        
                        NSArray *collecitonArr = json[@"AudioIDList"];
                        if ([collecitonArr isKindOfClass:[NSArray class]]) {
                            [[UserManager standerDefult].collectionMusicArr removeAllObjects];
                            [[UserManager standerDefult].collectionMusicArr addObjectsFromArray:collecitonArr];
                        }
                        NSArray *colleciton2Arr = json[@"AlbumIDList"];
                        if ([colleciton2Arr isKindOfClass:[NSArray class]]) {
                            [[UserManager standerDefult].collectionAlbumArr removeAllObjects];
                            [[UserManager standerDefult].collectionAlbumArr addObjectsFromArray:colleciton2Arr];
                        }
                        NSArray *colleciton3Arr = json[@"ShowIDList"];
                        if ([colleciton3Arr isKindOfClass:[NSArray class]]) {
                            [[UserManager standerDefult].collectionShowArr removeAllObjects];
                            [[UserManager standerDefult].collectionShowArr addObjectsFromArray:colleciton3Arr];
                        }
                        NSArray *praiseListArr = json[@"PraiseList"];
                        if ([praiseListArr isKindOfClass:[NSArray class]]) {
                            [[UserManager standerDefult].praiseListArr removeAllObjects];
                            [[UserManager standerDefult].praiseListArr addObjectsFromArray:praiseListArr];
                        }
                        
                        
                        NSDictionary *dic = @{@"openId":_openID,
                                              @"nickName":_nickName,
                                              @"picImg":_picImgName,
                                              @"type":num};
                        [[NSUserDefaults standardUserDefaults]setObject:dic forKey:@"three_login"];
                        [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"login_phone"];
                        [[NSUserDefaults standardUserDefaults]synchronize];
                        
                    }
                    //统计
                    NSString *provider = @"WX";
                    if ([num intValue] == 1) {
                        provider = @"WX";
                    }
                    else  if ([num intValue] == 2) {
                        provider = @"QQ";
                    }
                    else  if ([num intValue] == 3) {
                        provider = @"WB";
                    }
                    [MobClick profileSignInWithPUID:_openID provider:provider];
                    
                } failure:^(NSError *error) {

                }];
            }
        }
    }
}


- (void)applicationWillResignActive:(UIApplication *)application {
     [application beginBackgroundTaskWithExpirationHandler:NULL];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [application beginReceivingRemoteControlEvents];
    //后台远程控制，音乐播放
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application endReceivingRemoteControlEvents];
    //后台远程控制
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}

- (void)onAudioSessionEvent:(NSNotification *)noty
{
    if ([[noty.userInfo objectForKey:@"AVAudioSessionInterruptionTypeKey"] intValue] == 1) {
        if ([UserManager standerDefult].mainPlayer) {
            [[UserManager standerDefult].mainPlayer pause];
        }
    } else {
        if ([UserManager standerDefult].mainPlayer) {
            [[UserManager standerDefult].mainPlayer play];
        }
    }
}

#pragma mark -远程控制
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent
{
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        switch (receivedEvent.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:
                if ([UserManager standerDefult].mainPlayer) {
                    [[UserManager standerDefult].mainPlayer pause];
                }
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                if ([UserManager standerDefult].mainPlayer) {
                    [self onLoadMusic:YES];
                }
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                if ([UserManager standerDefult].mainPlayer) {
                    [self onLoadMusic:NO];
                }
                break;
            case UIEventSubtypeRemoteControlPause:
                if ([UserManager standerDefult].mainPlayer) {
                    [[UserManager standerDefult].mainPlayer pause];
                }
                break;
            case UIEventSubtypeRemoteControlPlay:
                if ([UserManager standerDefult].mainPlayer) {
                    [[UserManager standerDefult].mainPlayer play];
                }
                break;
            default:
                break;
        }
    }
}

- (void)onLoadMusic:(BOOL)isNext
{
    NSMutableArray *_musicArr = [UserManager standerDefult].musicArr;
    NSInteger _selectMusicIndex = [UserManager standerDefult].selectMusicIndex;
    AVPlayer *_mainPlayer = [UserManager standerDefult].mainPlayer;
    
    if (_musicArr.count > _selectMusicIndex) {
        if (isNext == YES) {
            //下一首
            ++_selectMusicIndex;
        } else {
            //上一首
            --_selectMusicIndex;
        }
        if (_selectMusicIndex >= _musicArr.count) {
            _selectMusicIndex = 0;
        }
        else if (_selectMusicIndex < 0) {
            _selectMusicIndex = _musicArr.count - 1;
        }
        
        [_mainPlayer pause];
        [[UserManager standerDefult]setSelectMusicIndex:_selectMusicIndex];
        
        //自动播放下一首，非播放器页面
        NSURL *urlPath;
        Music *music = [_musicArr objectAtIndex:_selectMusicIndex];
        [[UserManager standerDefult] setIsLastID:[NSString stringWithFormat:@"%@",music.ID]];
        if (music.isCacheData) {
            //读取沙盒已下载的音频
            NSString *filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",music.name]];
            if ([music.musicType intValue] >= 5) {
                filePath = [MusicCachesDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"qzx_%@.mp3",music.name]];
            }
            urlPath = [NSURL fileURLWithPath:filePath];
        } else {
            urlPath = [NSURL URLWithString:music.urlPath];
        }
        
        AVPlayerItem *item =[AVPlayerItem playerItemWithURL:urlPath];
        [_mainPlayer replaceCurrentItemWithPlayerItem:item];
        [_mainPlayer play];
        
        [self onAddMedia:music withAudio:_mainPlayer];
    }
}

//锁屏显示
- (void)onAddMedia:(Music *)currentMusic withAudio:(AVPlayer *)_audioPlayer
{
    Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
    if (playingInfoCenter) {
        
        NSMutableDictionary *songInfo = [ [NSMutableDictionary alloc] init];
        UIImage *img;
        if ([UserManager standerDefult].musicPlayType == MusicPLayType_Online) {
            //在线
            img = [UIImage imageNamed:@"diantai_play_bg"];
        } else {
            img = [UIImage imageNamed:@"yinping_play_bg"];
        }
        if (![currentMusic.CoverPath isKindOfClass:[NSNull class]]) {
            if (currentMusic.CoverPath.length > 0) {
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:currentMusic.CoverPath]];
                img = [UIImage imageWithData:data];
            }
        }
    
        NSString *singer;
        if ([UserManager standerDefult].audioPlayerType == AudioPLayerType_Qinzix) {
            NSArray *qzx_arr = [UserManager standerDefult].qinzixiuArr;
            NSInteger qzx_index = [UserManager standerDefult].selectMusicIndex;
            NSDictionary *qzx_dic = [qzx_arr objectAtIndex:qzx_index];
            singer = [NSString stringWithFormat:@"%@",[qzx_dic objectForKey:@"NickName"]];
        }
        else if ([UserManager standerDefult].audioPlayerType == AudioPLayerType_ZhuBo) {
            NSDictionary *zb_dic = [UserManager standerDefult].zhuboDic;
            singer = [NSString stringWithFormat:@"%@",[zb_dic objectForKey:@"NickName"]];
        } else {
            singer = currentMusic.Singer;
        }
        
        MPMediaItemArtwork *albumArt = [ [MPMediaItemArtwork alloc] initWithImage:img];
        
        [ songInfo setObject:currentMusic.name forKey:MPMediaItemPropertyTitle ];
        [ songInfo setObject:singer forKey:MPMediaItemPropertyArtist ];
        //        [ songInfo setObject: @"Audio Album" forKey:MPMediaItemPropertyAlbumTitle ];
        [ songInfo setObject: albumArt forKey:MPMediaItemPropertyArtwork ];
    
        //设置歌曲时长
        CMTime duration = _audioPlayer.currentItem.duration;
        if (duration.timescale > 0) {
            double totalTime = (_audioPlayer.currentItem.duration.value / _audioPlayer.currentItem.duration.timescale);
            [songInfo setObject:[NSNumber numberWithDouble:totalTime] forKey:MPMediaItemPropertyPlaybackDuration];
        }
        //设置已经播放时长
        CMTime current = _audioPlayer.currentItem.currentTime;
        if (current.timescale > 0) {
            double currentTime = (_audioPlayer.currentItem.currentTime.value / _audioPlayer.currentItem.currentTime.timescale);
            [songInfo setObject:[NSNumber numberWithDouble:currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
        }
        [ [MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo ];
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [application endBackgroundTask:UIBackgroundTaskInvalid];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
     [self saveContext];
}

/// 当网络状态发生变化时调用
- (void)appReachabilityChanged:(NSNotification *)notification{
    Reachability *reach = [notification object];
    if([reach isKindOfClass:[Reachability class]]){
        NetworkStatus status = [reach currentReachabilityStatus];

        if (reach == _hostReachability) {
            if ([reach currentReachabilityStatus] == NotReachable) {
                _networkStatus = NotReachable;
                [ErrorMessage showErrorMessage:@"网络已断开" inView:self.window];
            } else if (status == ReachableViaWiFi) {
                _networkStatus = ReachableViaWiFi;
            } else if (status == ReachableViaWWAN) {
                _networkStatus = ReachableViaWWAN;
            }
        }
        
    }
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CLShare" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CLShare.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}

- (NSManagedObjectContext *)managedObjectContext {
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            //NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

- (void)replaceSelectorForClass:(Class)cls
                  SelectorOriginal:(SEL)original
                   SelectorReplace:(SEL)replacement
                    withBlock:(id)block {
     
        IMP implementation = imp_implementationWithBlock(block);
        Method originalMethod = class_getInstanceMethod(cls, original);
        class_addMethod(cls, replacement, implementation, method_getTypeEncoding(originalMethod));
        Method replacementMethod = class_getInstanceMethod(cls, replacement);
        if (class_addMethod(cls, original, method_getImplementation(replacementMethod), method_getTypeEncoding(replacementMethod))) {
                class_replaceMethod(cls, replacement, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
            } else {
                    method_exchangeImplementations(originalMethod, replacementMethod);
                }
         
}

- (void)preventImagePickerCrashOn3DTouch {
        // Load PhotosUI and bail if 3D Touch is unavailable.
        // (UIViewControllerPreviewing may be redundant,
        // as PUPhotosGridViewController only seems to exist on iOS 9,
        // but I'm being cautious.)
        NSString *photosUIPath = @"/System/Library/Frameworks/PhotosUI.framework";
        NSBundle *photosUI = [NSBundle bundleWithPath:photosUIPath];
        Class photosClass = [photosUI classNamed:@"PUPhotosGridViewController"];
        if (!(photosClass && objc_getProtocol("UIViewControllerPreviewing"))) {
                return;
            }
     
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
     
        SEL selector = @selector(ab_previewingContext:viewControllerForLocation:);
        [self replaceSelectorForClass:photosClass
                          SelectorOriginal:@selector(previewingContext:viewControllerForLocation:)
                           SelectorReplace:selector
                                 withBlock:^UIViewController *(id self, id previewingContext, CGPoint location) {
              
                     // Default implementation throws on iOS 9.0 and 9.1.
                     @try {
//                             NSLog(@"Replace method at runtime to prevent UIImagePicker crash on 3D Touch.");
                             return ((UIViewController *(*)(id, SEL, id, CGPoint))objc_msgSend)(self, selector, previewingContext, location);
                         } @catch (NSException *e) {
                                 return nil;
                             }
                 }];
     
#pragma clang diagnostic pop
}

@end
